<link rel="stylesheet" type="text/css" href="<?= $base_url ?>css/fmis/document/view.css">

<div class="document">
    <div class="view">
        <div class="tab-pane active" id="upload">
            <div class="container-fluid">
                <div class="col-lg-3">
                    <h3>Upload a File</h3>
                    <form action="<?= $base_url?>fmis/document/upload/document" class="padding-top-30" method="post" enctype="multipart/form-data" id="formupload">
                        <label for="p_filename">File Selected:</label>
                        <p id="p_filename">No File Selected Yet</p>
                        <label for="p_filetype">Type:</label>
                        <p id="p_filetype">No File Selected Yet</p>
                        <label for="p_filesize">Size:</label>
                        <p id="p_filesize">No File Selected Yet</p>
                        </br>
                        <label for="p_filerename">Rename File:</label>
                        <input type="text" id="p_filerename" name="p_filerename">
                        </br>
                        <label for="document" class="button">Choose File</label>
                        </br>
                        </br>
                        <label class="button button-primary disabled" id="submitupload">Upload</label>
                        <input type="file" name="document" id="document" style="opacity:0;">
                    </form>
                </div>
                <div class="col-lg-9">
                    <h3>Uploaded Documents</h3>
                    <div class="document-results">
                        <?php foreach($uploads_owner as $doc) {
                            $id = $doc['DocumentID'];
                            $documentNam = $doc['DocumentName'];
                            $uploaderNam = $doc['UploaderName'];
                            $date = $doc['DateUploaded'];
                            $publicityName = $doc['PublicityName'];
                            $publicityID = $doc['PublicityID'];
                            $origName = $doc['OriginalName'];
                            $desc = $doc['Description'];
                            ?>
                        <div id="document<?= $id?>" class="document-result" documentID="<?= $id?>">
                            <div class="content-holder container-fluid" >
                                <div class="details col-lg-6">
                                    <p class="documentname">
                                        Document Name: <?= $documentNam?>
                                        <input type="hidden" value=" <?= $documentNam?>">
                                    </p>
                                    <p class="uploadername">
                                        Uploader Name: <?= $uploaderNam?>
                                        <input type="hidden" value=" <?= $uploaderNam?>">
                                    </p>
                                    <p class="dateuploaded">
                                        Date Uploaded: <?= $date?>
                                        <input type="hidden" value=" <?= $date?>">
                                    </p>
                                    <p class="status" publicityid="<?= $publicityID?>">
                                        Publicity: <?= $publicityName?>
                                    </p>
                                    <p class="originalname">
                                        Original Document Name: <?= $origName?>
                                        <input type="hidden" value=" <?= $origName?>">
                                    </p>
                                </div>
                                <div class="description col-lg-6">
                                    <label for="input-description">Description: </label>
                                    <textarea id="input-description" name="input-description" value="<?= $desc?>" readonly><?= $desc?></textarea>
                                </div>
                                <div class="clear-both"></div>
                                <div class="control-holder">
                                    <button class="button button-primary" id="btnDownload">Download Document</button>
                                    <button class="button" id="btnEdit">Edit Details</button>
                                    <button class="button" id="btnDelete">Delete</button>
                                </div>
                            </div>
                        </div>
                        <?php } ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="growlUI"></div>
<div id="dialog-editdetails" title="Edit Details">
    <form action="<?= $base_url?>fmis/document/editdetail" method="post" id="formeditdetail">
        <label for="edit_document_name">Document Name: </label>
        <textarea id="edit_document_name" name="edit_document_name">asdf</textarea>

        <label for="edit_document_publicity">Publicity: </label>
        <select id="edit_document_publicity" name="edit_document_publicity">
            <?php foreach($publicity as $public){ ?>
                <option value="<?= $public['PublicityID']?>"><?= $public['Description']?></option>
            <?php } ?>
        </select>

        <label for="edit_document_description">Document Description: </label>
        <textarea id="edit_document_description" name="edit_document_description">adf</textarea>
    </form>
</div>
<div id="dialog-delete">
    <p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Are you sure you want to delete this? This cannot be undone.</p>
</div>

<div id="dialog-sorry" title="Warning">
    <p>
        <span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Sadly, this functionality wasn't finished.
    </p>
</div>

<script>
    $(function() {
        $( "#dialog-editdetails" ).dialog({
            autoOpen: false,
            resizable: false,
            height:600,
            width: 600,
            modal: true,
            buttons: {
                "Save Edit": function() {

                    var form = $('#formeditdetail');

                    $.ajax({
                        url: form.attr('action') + '/' + selectedEditId,
                        type: "POST",
                        data: form.serialize(),
                        dataType: 'json',
                        processData: false,
                        success: function (data, textStatus, jqXHR)
                        {
                            console.log(data);
                            if(data.success)
                            {
                                growl("Success", "Document Details Edited", "check48");

                                setTimeout(function(){window.location.replace('<?= $base_url?>fmis/document/view')}, 2300);
                            }
                            else
                            {
                                growl("Error", data.message, 'error48');
                            }
                        },
                        error: function(jqXHR, textStatus, errorThrown)
                        {
                            console.log(jqXHR);
                            console.log(textStatus);
                            console.log(errorThrown);
                        }
                    });

                    $( this ).dialog( "close" );


                },
                Cancel: function() {
                    $( this ).dialog( "close" );
                }
            }
        });

        $( "#dialog-delete" ).dialog({
            autoOpen: false,
            resizable: false,
            height:200,
            width: 400,
            modal: true,
            buttons: {
                "Yes": function() {

                    $.ajax({
                        url: '<?= $base_url?>fmis/document/delete/' + selectedDeleteId,
                        dataType: 'json',
                        success: function (data, textStatus, jqXHR)
                        {
                            console.log(data);
                            if(data.success)
                            {
                                growl("Success", "Document Deleted", "check48");

                                setTimeout(function(){window.location.replace('<?= $base_url?>fmis/document/view')}, 2300);
                            }
                            else
                            {
                                growl("Error", data.message,"check48");
                            }
                        },
                        error: function(jqXHR, textStatus, errorThrown)
                        {
                            console.log(jqXHR);
                            console.log(textStatus);
                            console.log(errorThrown);
                        }
                    });
                    $( this ).dialog( "close" );
                },
                No: function() {
                    $( this ).dialog( "close" );
                }
            }
        });

        $( "#dialog-sorry" ).dialog({
            autoOpen: false,
            resizable: false,
            height:200,
            width: 300,
            modal: true,
            buttons: {
                Ok: function() {
                    $( this ).dialog( "close" );
                }
            }
        });
    });

    var base_url = '<?php echo($base_url)?>';
    var selectedEditId;
    var selectedDeleteId;
    var selectedDownloadId;

    $('#btnDelete').on('click', function(event){
        event.preventDefault();

        clicked = $(this);

        var result = clicked.closest('.document-result');
        selectedDeleteId = result.attr('documentid');

        console.log(selectedDeleteId);
        $('#dialog-delete').dialog('open');
    });

    $('#btnDownload').on('click', function(event){
        event.preventDefault();

        clicked = $(this);

        var result = clicked.closest('.document-result');
        selectedDownloadId = result.attr('documentid');

        window.location.assign('<?= $base_url?>fmis/document/download/' + selectedDownloadId);
    });

    $('#btnSearch').on('click', function(e){
        e.preventDefault();
        $( "#dialog-sorry" ).dialog('open');
    });

    $('#btnEdit').on('click', function(event){
        $( "#dialog-editdetails" ).dialog('open');
        clicked = $(this);

        var result = clicked.closest('.document-result');
        var documentname = result.find('.documentname input').val();
        var publicity = result.find('.status').attr('publicityid');
        var description = $('#input-description').val();
        selectedEditId = result.attr('documentid');

        console.log(selectedEditId);
        console.log(result);
        console.log(description);
        console.log(documentname);
        console.log(publicity);

        $('#edit_document_name').val(documentname);
        $('#edit_document_publicity').val(publicity);
        $('#edit_document_description').val(description);


    });

    $('#submitupload').on('click', function(event){

        if($(this).hasClass('disabled'))
        {
            event.preventDefault();
            return;
        }

       $('#formupload').submit();
    });

    $('#formupload').on('submit', function (event){

        event.stopPropagation();
        event.preventDefault();


        var files = filesToUpload;
        console.log(filesToUpload)
        var form = $('#formupload');
        // Create a formdata object and add the files
        var data = new FormData(form[0]);

        $.ajax({
            url: form.attr('action'),
            type: "POST",
            data: data,
            dataType: 'json',
            processData: false,
            contentType: false,
            success: function (data, textStatus, jqXHR)
            {
                console.log(data);
                if(data.success)
                {
                    setTimeout(function(){window.location.replace('<?= $base_url?>fmis/document/view')}, 2300);
                    growl(data.page_title, data.message, "check48");
                }
                else
                {
                    growl(data.page_title, data.message, "error48");
                }
            },
            error: function(jqXHR, textStatus, errorThrown)
            {
                // Handle errors here
                console.log('ERRORS: ' + textStatus);
                // STOP LOADING SPINNER
            }
        });
    });

    var filesToUpload;

    $('#document').on('change', function(event){
    //console.log($(this).val().split(/(\\|\/)/g).pop());
        file = this.files[0];
        filesToUpload = event.target.files;
        name = file.name;//console.log(files.name);
        size = file.size / 1000000;//console.log(files.size);
        type = file.type;//console.log(files.type);

        $('#p_filerename').val(name);
        $('#p_filename').html(name);
        $('#p_filetype').html(type);
        $('#p_filesize').html(size.toFixed(3) + "MB");

        $('#submitupload').attr('class', 'button button-primary enabled');

    });
</script>